package com.freewater.javabase.demo.network.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.nio.charset.StandardCharsets;

public class Server {
    public static void main(String[] args) throws IOException {
        DatagramSocket ds = new DatagramSocket(6666);
        System.out.println("Server started...");
        while (true) {
            byte[] buffer = new byte[1024];
            DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
            ds.receive(dp);

            System.out.println("received package from " + dp.getAddress());
            String s = new String(dp.getData(), dp.getOffset(), dp.getLength(), StandardCharsets.UTF_8);
            System.out.println("received: " + s);

            // 当服务器收到一个DatagramPacket后，通常必须立刻回复一个或多个UDP包，因为客户端地址在DatagramPacket中，
            // 每次收到的DatagramPacket可能是不同的客户端，如果不回复，客户端就收不到任何UDP包。
            byte[] data = "ack".getBytes(StandardCharsets.UTF_8);
            dp.setData(data);
            ds.send(dp);
        }
    }
}
